package com.infinit.easyreader.Biz;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.infinit.easyreader.dao.RankDao;
import com.infinit.easyreader.entity.ContentType;
import com.infinit.easyreader.entity.RankTime;
import com.infinit.easyreader.entity.RankType;
import com.infinit.easyreader.utils.Consts;
import com.infinit.easyreader.utils.NetUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类：com.infinit.easyreader.Biz.OnlineRankTypeBiz V[1.0.0]
 * 作用：处理在线排行的分类信息
 * Created by rzy on 2016/6/26.
 */
public class OnlineRankTypeBiz implements Consts {
    public static final int CODE_ERROR = 101;
    public static final int CODE_SUCCESS = 102;
    public static final String KEY_RANK = "rankKey";
    public static final String KEY_RANKTIME = "rankTimeKey";
    public static final String PREFRENCE_RANK_TIME = "pRankTime";
    Map<String, Object> rankMap = new HashMap<>();
    private NetUtils netUtils;
    private Activity activity;
    private Handler handler;
    private RankDao rankDao;

    public OnlineRankTypeBiz(Activity activity, Handler handler) {
        netUtils = NetUtils.getInstance();
        this.activity = activity;
        this.handler = handler;
        rankDao = new RankDao(activity);
    }


    /**
     * 获取Rank数据
     */


    public void getRankInfo() {
        //检查更新时间
        SharedPreferences preferences = activity.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        long lastSaveTime = preferences.getLong(PREFRENCE_RANK_TIME, 0);
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - lastSaveTime <= 24 * 60 * 60 * 1000) {
            rankDao.clearData();
            getOnlineRankType();
            //写入更新时间
            SharedPreferences.Editor editor = preferences.edit();
            editor.putLong(PREFRENCE_RANK_TIME, Calendar.getInstance().getTimeInMillis());
            editor.apply();
            return;
        }
        getRankTypeFromDataBase();
        rankDao.close();
    }


    /**
     * 从数据库中获取Rank的相关信息
     */

    public void getRankTypeFromDataBase() {
        List<RankType> rankTypes = rankDao.getAllRankType();
        List<String> rankNames = new ArrayList<>();
        List<String> rankTimeList = new ArrayList<>();
        for (RankType rTYPE : rankTypes) {
            rankNames.add(rTYPE.getRankName());
        }
        List<RankTime> rankTimes = rankDao.getAllRankTime();
        for (RankTime rTime : rankTimes) {
            rankTimeList.add(rTime.getRankTimeName());
        }
        rankMap.put(KEY_RANK, rankNames);
        rankMap.put(KEY_RANKTIME, rankTimeList);
        Message.obtain(handler, CODE_SUCCESS, rankMap).sendToTarget();
    }


    /**
     * 获取在线的排行数据
     */

    public void getOnlineRankType() {
        StringRequest rankTimeRequest = new StringRequest(url, new RankTypeRequestListener(), new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Message.obtain(handler, CODE_ERROR).sendToTarget();
            }
        });
        netUtils.addRequest(rankTimeRequest, activity);
    }


    private class RankTypeRequestListener implements Response.Listener<String> {

        @Override
        public void onResponse(String response) {
            //解析返回的结果
            try {
                JSONObject object = new JSONObject(response);
                if (object.getInt("error_code") != 0) {
                    Message.obtain(handler, CODE_ERROR).sendToTarget();
                } else {
                    //开始解析数据
                    JSONObject resultObject = object.getJSONObject("result").getJSONObject("GetRankTypeRsp");
                    JSONArray rankArray = resultObject.getJSONObject("RankList").getJSONArray("Rank");

                    //解析Rank数据
                    Gson mGson = new Gson();
                    List<String> rankNameList = new ArrayList<>();
                    List<RankType> rankTypeList = new ArrayList<>();
                    for (int i = 0; i < rankArray.length(); i++) {
                        RankType rankType = mGson.fromJson(rankArray.getString(i), RankType.class);
                        rankNameList.add(rankType.getRankName());
                        rankTypeList.add(rankType);
                    }
                    //将rankNameList传输到Activity
                    rankMap.put(KEY_RANK, rankNameList);
                    //将RankType信息保存到数据库中
                    rankDao.insertRankInfo(rankTypeList);
                    //解析RankTime数据
                    JSONArray rankTimeArray = resultObject.getJSONObject("RankTimeList").getJSONArray("RankTime");
                    //解析RankTime数据
                    List<RankTime> rankTimeList = new ArrayList<>();
                    List<String> rankTimeNameList = new ArrayList<>();
                    for (int i = 0; i < rankTimeArray.length(); i++) {
                        RankTime rankTime = mGson.fromJson(rankTimeArray.getString(i), RankTime.class);
                        rankTimeNameList.add(rankTime.getRankTimeName());
                        rankTimeList.add(rankTime);
                    }
                    //将RankTimes数据插入到数据库
                    rankDao.insertRankInfo(rankTimeList);
                    rankMap.put(KEY_RANKTIME, rankTimeNameList);

                    //解析ContentType的数据
                    JSONArray contentTypeArray = resultObject.getJSONObject("ContentTypeList").getJSONArray("ContentType");
                    List<ContentType> contentTypes = new ArrayList<>();
                    for (int i = 0; i < contentTypeArray.length(); i++) {
                        ContentType contentType = mGson.fromJson(contentTypeArray.getString(i), ContentType.class);
                        contentTypes.add(contentType);
                    }
                    rankDao.insertRankInfo(contentTypes);

                    Message.obtain(handler, CODE_SUCCESS, rankMap).sendToTarget();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    }
}
